type FunProp = (data: any) => void;
interface IOption {
  size: number;
  scale: number;
}
var imgToBase64 = (file: File): Promise<string> => {
  // 用FileReader读取文件
  var reader = new FileReader();
  return new Promise((resolve, reject) => {
    if (file) {
      reader.readAsDataURL(file);
      reader.onload = function (evt) {
        if (evt.target) {
          resolve(evt.target.result as string);
        }
      };
    }
  });
};

//base64转换为file对象
function base64toFile(dataurl: string, filename: string): File | undefined {
  //将base64转换为文件
  var arr = dataurl.split(",");
  if (arr.length > 0) {
    // @ts-ignore
    var mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
  }
}
export var compressImg = async function (file: File, options: IOption) {
  var imgname = file.name;
  var imgtype = imgname.substring(imgname.lastIndexOf(".") + 1).toLowerCase();
  if (imgtype == "jpg" || imgtype == "jpeg") {
    imgtype = "image/jpeg";
  } else {
    imgtype = "image/png";
  }
  let base64 = await imgToBase64(file);
  return new Promise((resolve, reject) => {
    // 创建图片对象
    var img = new Image();
    // 用图片对象加载读入的base64
    img.src = base64;
    img.onload = function () {
      var that = this,
        canvas = document.createElement("canvas"),
        ctx = canvas.getContext("2d");
      // @ts-ignore
      canvas.setAttribute("width", that.width);
      // @ts-ignore
      canvas.setAttribute("height", that.height);
      // 将图片画入canvas
      // @ts-ignore
      ctx.drawImage(that, 0, 0, that.width, that.height);

      // 压缩到指定体积以下（M）
      if (options.size) {
        var scale = 0.9;
        (function f(scale) {
          if (base64.length / 1024 / 1024 > options.size && scale > 0) {
            base64 = canvas.toDataURL(imgtype, scale);
            scale = scale - 0.1;
            f(scale);
          } else {
            resolve(base64toFile(base64, imgname));
          }
        })(scale);
      } else if (options.scale) {
        // 按比率压缩
        base64 = canvas.toDataURL(imgtype, options.scale);
        resolve(base64toFile(base64, imgname));
      }
    };
  });
};
